package com.gehj.androidlibs;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gehj.base.BaseActivity;
import com.gehj.uhttp.GlobleURL;
import com.gehj.uhttp.OkhttpUtils;
import com.gehj.uhttp.listener.DisposeDataListener;

import java.io.IOException;
import java.lang.ref.WeakReference;

import okhttp3.Response;

/**
 * @ClassName: MainActivity
 * @Description: 以下主要功能
 * 1，自己封装okhttp测试 内存泄漏测试
 * 2，Okhttp取消请求 模板
 * 3，handler 取消请求 - 防止内存泄漏
 * @Author: gehj
 * @CreateDate: 2020/12/15 14:43
 */

public class MainActivity_handler extends AppCompatActivity {
    private static final String TAG = "MainActivity_handler";
    private TextView textView;
    //private WeakHandler mHandler = new WeakHandler<MainActivity_handler>(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_handler);

        textView = (TextView) findViewById(R.id.text);
        OkhttpUtils.Get_common(GlobleURL.banner, new DisposeDataListener() {
            @Override
            public void onFailure(String errorMsg) {

            }

            @Override
            public void onSuccess(Response response) {
                try {
                    String json = response.body().string();
                    Message message = Message.obtain();
                    message.what = 0;
                    message.obj = json;
                    //message可以传其他数据
                    /*Bundle bundle = new Bundle();
                    bundle.putString("filePath",filePath);
                    bundle.putString("fileName",fileName);*/
                    // message.setData(bundle);
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }


    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                //处理法过来来的消息
                String s = (String) msg.obj;
                textView.setText(s);
                //msg.getData();

            }
        }
    };

    @Override
    protected void onDestroy() {

        OkhttpUtils.cancelAllCall();//防止内存泄漏进
        handler.removeCallbacksAndMessages(null); //防止内存泄漏进

        super.onDestroy();
    }


}